package com.woniuxy.util;

import com.nimbusds.jose.JWSObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Map;

/**
 * @author ：CuiYC
 * @description：
 * @date ：Created in 2025/3/13 15:14
 * @modified By：
 */
public class UserContext {
    public static Integer getUserId() throws ParseException {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String jwt = request.getHeader("token");

        JWSObject jwsObject = JWSObject.parse(jwt); //反序列化方法
        Map<String, Object> userMap = jwsObject.getPayload().toJSONObject(); //得到用户信息
        Long userId = (Long) userMap.get("id");
        return userId.intValue(); //得到用户ID
    }
}
